
package me.zhengjie.service.impl;

import me.zhengjie.base.AjaxResult;
import me.zhengjie.domain.AppHoliday;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.AppHolidayRepository;
import me.zhengjie.service.AppHolidayService;
import me.zhengjie.service.dto.AppHolidayDto;
import me.zhengjie.service.dto.AppHolidayQueryCriteria;
import me.zhengjie.service.mapstruct.AppHolidayMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author IQW
* @date 2022-07-18
**/
@Service
@RequiredArgsConstructor
public class AppHolidayServiceImpl implements AppHolidayService {

    private final AppHolidayRepository appHolidayRepository;
    private final AppHolidayMapper appHolidayMapper;
    private final UserService userService;
    private final DictDetailService dictDetailService;

    @Override
    public Map<String,Object> queryAll(AppHolidayQueryCriteria criteria, Pageable pageable){
        Page<AppHoliday> page = appHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(appHolidayMapper::toDto));
    }

    @Override
    public Map queryAllApi(AppHolidayQueryCriteria criteria, Pageable pageable){
        Page<AppHoliday> page = appHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Map ret = PageUtil.toPage(page.map(appHolidayMapper::toDto));
        return AjaxResult.success(ret);
    }

    @Override
    public Map queryAppHolidayCate(){

        List<DictDetail> list = dictDetailService.queryAllBydictId(18L);
        List<Map> rets = new ArrayList<>();
        list.forEach(item->{
            Map<String, Object> ret = new HashMap<>();
            ret.put("id",item.getValue());
            ret.put("name",item.getLabel());
            rets.add(ret);
        });
        return AjaxResult.success(rets);
    }

    @Override
    public List<AppHolidayDto> queryAll(AppHolidayQueryCriteria criteria){
        return appHolidayMapper.toDto(appHolidayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public AppHolidayDto findById(Integer holId) {
        AppHoliday appHoliday = appHolidayRepository.findById(holId).orElseGet(AppHoliday::new);
        ValidationUtil.isNull(appHoliday.getHolId(),"AppHoliday","holId",holId);
        return appHolidayMapper.toDto(appHoliday);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppHolidayDto create(AppHoliday resources) {
        return appHolidayMapper.toDto(appHolidayRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map add(AppHoliday resources) {
        if(     StringUtils.isEmpty(resources.getNickName()) || StringUtils.isEmpty(resources.getCate()) ||
                StringUtils.isEmpty(resources.getContent())  || StringUtils.isNull(resources.getUserId1()) ||
                StringUtils.isNull(resources.getStartTime()) || StringUtils.isNull(resources.getEndTime())
        ){
            return AjaxResult.error("参数错误");
        }
        //处理参数
        resources.setUserId(SecurityUtils.getCurrentUserId().intValue());
        //查询用户信息
        UserDto user = userService.findById(resources.getUserId());
        if(null!=user){
//            resources.setNickName(user.getNickName());
            resources.setAvatarPath(StringUtils.getUserHead(user.getAvatarPath()));
            resources.setWorkNo(user.getWorkNo());
            resources.setPhone(user.getPhone());
        }
        //查询用户信息2
        user = userService.findById(resources.getUserId1());
        if(null!=user){
            resources.setNickName1(user.getNickName());
            resources.setAvatarPath1(StringUtils.getUserHead(user.getAvatarPath()));
        }

        //查询用户信息3
        user = userService.findById(resources.getUserId2());
        if(null!=user){
            resources.setNickName2(user.getNickName());
            resources.setAvatarPath2(StringUtils.getUserHead(user.getAvatarPath()));
        }
        //查询字典
        DictDetail d = dictDetailService.queryAllBydictIdAndValue(18L,resources.getCate());
        if(null != d){
            resources.setTitle(d.getLabel());
        }
        resources.setStatus(0);
        resources.setDays(DateUtils.getHolidayPoor(resources.getEndTime(),resources.getStartTime()));
        resources.setCreateTime(DateUtils.getNowTimestamp());

        appHolidayRepository.save(resources);
        return AjaxResult.success("提交成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map act(AppHoliday resources) {

        AppHoliday appHoliday = appHolidayRepository.findById(resources.getHolId()).orElseGet(AppHoliday::new);
        if(null == appHoliday)
        {
            return AjaxResult.error("数据不存在");
        }
        if(!appHoliday.getUserId1().equals(SecurityUtils.getCurrentUserId().intValue())){
            return AjaxResult.error("无权审批");
        }

        appHoliday.setReply(resources.getReply());
        appHoliday.setReplyTime(DateUtils.getNowTimestamp());
        appHoliday.setStatus(resources.getStatus());
        appHolidayRepository.save(appHoliday);
        return AjaxResult.success("审批成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map cancel(AppHoliday resources) {

        AppHoliday appHoliday = appHolidayRepository.findById(resources.getHolId()).orElseGet(AppHoliday::new);
        if(null == appHoliday)
        {
            return AjaxResult.error("数据不存在");
        }
        if(!appHoliday.getUserId().equals(SecurityUtils.getCurrentUserId().intValue())){
            return AjaxResult.error("无权操作");
        }
        appHoliday.setStatus(3);
        appHolidayRepository.save(appHoliday);
//        appHolidayRepository.deleteById(appHoliday.getHolId());
        return AjaxResult.success("取消成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AppHoliday resources) {
        AppHoliday appHoliday = appHolidayRepository.findById(resources.getHolId()).orElseGet(AppHoliday::new);
        ValidationUtil.isNull( appHoliday.getHolId(),"AppHoliday","id",resources.getHolId());
        //处理时间
        resources.setUpdateTime(DateUtils.getDayEndTimestamp());
        appHoliday.copy(resources);
        appHolidayRepository.save(appHoliday);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer holId : ids) {
            appHolidayRepository.deleteById(holId);
        }
    }

    @Override
    public void download(List<AppHolidayDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppHolidayDto appHoliday : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("责任区ID", appHoliday.getAreaId());
            map.put("用户ID", appHoliday.getUserId());
            map.put("申请人", appHoliday.getNickName());
            map.put("头像", appHoliday.getAvatarPath());
            map.put("工号", appHoliday.getWorkNo());
            map.put("手机号码", appHoliday.getPhone());
            map.put("类别", appHoliday.getTitle());
            map.put("请假理由", appHoliday.getContent());
            map.put("开始时间", appHoliday.getStartTime());
            map.put("结束时间", appHoliday.getEndTime());
            map.put("天数", appHoliday.getDays());
            map.put("状态 0待审批、1通过、2不通过、3撤销", appHoliday.getStatus());
            map.put(" createTime",  appHoliday.getCreateTime());
            map.put(" updateTime",  appHoliday.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}